package com.billing.utils;

import com.squareup.okhttp.*;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class OkhttpUtils {

    public static String postBody(String url, String body) {
        MediaType JSON = MediaType.parse("text/x-markdown; charset=utf-8");
        return post(JSON, url, body);
    }

    private static String post(MediaType mediaType, String url, String body) {
        //申明给服务端传递一个json串
        //创建一个OkHttpClient对象
        OkHttpClient okHttpClient = getOkHttpClientIntance();
        //创建一个RequestBody(参数1：数据类型 参数2传递的json串)
        RequestBody requestBody = RequestBody.create(mediaType, body);
        //创建一个请求对象
        final Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        //发送请求获取响应
        try {
            Response response = okHttpClient.newCall(request).execute();
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }


    private static OkHttpClient mOkhttpClient;

    private static synchronized OkHttpClient getOkHttpClientIntance() {
        if (mOkhttpClient == null) {
            mOkhttpClient = new OkHttpClient();
            mOkhttpClient.setConnectTimeout(15, TimeUnit.SECONDS);
            mOkhttpClient.setWriteTimeout(15, TimeUnit.SECONDS);
            mOkhttpClient.setReadTimeout(15, TimeUnit.SECONDS);
        }
        return mOkhttpClient;
    }

}